<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '商品收藏',
    backgroundColor: '#f5f5f5',
    enablePullDownRefresh: true,
  },
}
</route>

<template>
  <view class="collect-page">
    <scroll-view
      class="collect-list"
      scroll-y
      refresher-enabled
      @refresherrefresh="onRefresh"
      @scrolltolower="loadMore"
    >
      <HorizontalSKu
        v-for="item in collectList"
        :key="item.id"
        :item="item"
        @delete="handleDelete"
      ></HorizontalSKu>
      <wd-divider v-if="isEmpty">暂无收藏商品</wd-divider>
      <wd-divider v-else-if="isLoading">加载中...</wd-divider>
      <wd-divider v-else>没有更多了</wd-divider>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { GoodsSku } from '@/service/goods/goods.d'
import { deleteCollect, getCollections } from '@/service/goods/collect/collect'

const HorizontalSKu = defineAsyncComponent(
  () => import('@/pages/goods/components/horizontalSKu.vue'),
)
// 状态管理
const collectList = ref<GoodsSku[]>([])
const currentPage = ref(1)
const pageSize = 10
const isLoading = ref(false)
const isLastPage = ref(false)

// 初始化加载
onLoad(async () => {
  await loadData(true)
})

// 核心数据加载方法
const loadData = async (reset = false) => {
  if (isLoading.value || (isLastPage.value && !reset)) return

  try {
    isLoading.value = true
    const page = reset ? 1 : currentPage.value

    // 调用真实接口
    const { data } = await getCollections({
      current: page,
      size: pageSize,
    })

    if (reset) {
      collectList.value = data.records
    } else {
      collectList.value = [...collectList.value, ...data.records]
    }

    // 分页状态判断
    isLastPage.value = data.current * data.size >= data.total
    currentPage.value = data.current + 1
  } catch (error) {
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none',
    })
  } finally {
    isLoading.value = false
    uni.stopPullDownRefresh()
  }
}

// 删除收藏处理
const handleDelete = async (id: number) => {
  try {
    await uni.showModal({
      title: '确认删除',
      content: '确定要移除该收藏商品吗？',
      confirmText: '删除',
    })

    await deleteCollect(id)

    await loadData()
    uni.showToast({ title: '删除成功' })
  } catch (error) {
    if (error.errMsg !== 'showModal: cancel') {
      uni.showToast({
        title: '删除失败，请重试',
        icon: 'none',
      })
    }
  }
}

// 下拉刷新
const onRefresh = () => loadData(true)

// 滚动加载
const loadMore = () => {
  if (!isLastPage.value) loadData()
}

// 计算属性
const isEmpty = computed(() => collectList.value.length === 0 && !isLoading.value)
</script>

<style lang="scss" scoped>
.collect-page {
  box-sizing: border-box;
  height: 100vh;
}

.collect-list {
  box-sizing: border-box;
  width: 750rpx;

  .collect-item {
    margin: 15rpx;
    overflow: hidden;
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  }
}
</style>
